package com.yang.sso.oauth.controller;

import com.yang.sso.oauth.enums.ResultCode;
import com.yang.sso.oauth.result.Result;
import lombok.RequiredArgsConstructor;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

/**
 *  授权成功后的操作接口
 * @author: Islands
 * @create: 2024-04-13 23:24
 */

@RestController
@RequiredArgsConstructor
public class UserInfoController {
    private final TokenStore tokenStore;
    private final HttpServletRequest request;

    /**
     * 获取用户信息
     * @return Result<?>
     */
    @GetMapping("/userInfo")
    public Result<?> userInfo() {
        String authHeader = request.getHeader("Authorization");
        if (authHeader != null) {
            String token = authHeader.replace("Bearer", "").trim();
            // 使用TokenStore从数据库或缓存中获取令牌
            OAuth2AccessToken oAuth2AccessToken = tokenStore.readAccessToken(token);
            // 验证令牌是否存在和有效，并构建响应对象
            if (oAuth2AccessToken != null && !oAuth2AccessToken.isExpired()) {
                Map<String, Object> map = oAuth2AccessToken.getAdditionalInformation();
                return Result.success(map);
            }
        }
        return Result.failed("无效用户");
    }

}
